import type { RequestConfig, ResponseData } from './types/api'

// 创建请求实例
const request = <T>(config: RequestConfig): Promise<ResponseData<T>> => {
  return new Promise((resolve, reject) => {
    const {
      url,
      method = 'GET',
      data = {},
      header = {},
      timeout = 15000
    } = config

    // 添加全局请求头（如 token）
    const globalHeaders = {
      'Content-Type': 'application/json',
      'Authorization': uni.getStorageSync('token') || ''
    }

    uni.request({
      url: getFullUrl(url),
      method,
      data,
      header: { ...globalHeaders, ...header },
      timeout,
      success: (res) => {
        // 状态码 2xx 范围表示成功
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data as ResponseData<T>)
        } else {
          handleError(res, reject)
        }
      },
      fail: (err) => {
        reject({
          code: -1,
          message: '网络连接失败',
          data: err
        })
      }
    })
  })
}

// 处理错误响应
const handleError = (res: UniApp.RequestSuccessCallbackResult, reject: any) => {
  const status = res.statusCode
  let message = '请求错误'

  switch (status) {
    case 401:
      message = '未授权，请重新登录'
      uni.navigateTo({ url: '/pages/login/index' })
      break
    case 403:
      message = '拒绝访问'
      break
    case 404:
      message = '请求资源不存在'
      break
    case 500:
      message = '服务器错误'
      break
  }

  reject({
    code: status,
    message,
    data: res.data
  })
}

// 获取完整 URL
const getFullUrl = (url: string): string => {
  if (/^https?:\/\//.test(url)) return url
  return `${import.meta.env.VITE_API_BASE_URL}${url}`
}

// 封装常用方法
export const get = <T>(url: string, params?: object, config?: Omit<RequestConfig, 'url' | 'method' | 'data'>) => 
  request<T>({ url, method: 'GET', data: params, ...config })

export const post = <T>(url: string, data?: object, config?: Omit<RequestConfig, 'url' | 'method' | 'data'>) => 
  request<T>({ url, method: 'POST', data, ...config })

export const put = <T>(url: string, data?: object, config?: Omit<RequestConfig, 'url' | 'method' | 'data'>) => 
  request<T>({ url, method: 'PUT', data, ...config })

export const del = <T>(url: string, data?: object, config?: Omit<RequestConfig, 'url' | 'method' | 'data'>) => 
  request<T>({ url, method: 'DELETE', data, ...config })

export default request